# 第二课堂管理系统菜单结构修复工具
# 创建于2025年3月14日

Write-Host "========================================"
Write-Host "第二课堂管理系统菜单结构修复工具" -ForegroundColor Cyan
Write-Host "创建于2025年3月14日"
Write-Host "========================================"
Write-Host ""

# 设置数据库连接参数
$DB_USER = "root"
$DB_PASSWORD = "123456"
$DB_NAME = "scms"
$DB_HOST = "localhost"
$DB_PORT = "3306"

# 检查是否安装了MySQL客户端
if (-not (Get-Command mysql -ErrorAction SilentlyContinue)) {
    Write-Host "[错误] 未找到MySQL客户端。请确保已安装MySQL客户端并添加到PATH环境变量中。" -ForegroundColor Red
    exit
}

# 1. 检查当前系统运行状态
Write-Host "[1/4] 检查当前系统运行状态..." -ForegroundColor Yellow
$runningPort = Get-NetTCPConnection -LocalPort 8089 -ErrorAction SilentlyContinue
if ($runningPort) {
    Write-Host "[警告] 系统当前正在运行，建议关闭系统后再执行修复操作。" -ForegroundColor Yellow
    $continue = Read-Host "是否继续执行修复操作？(Y/N)"
    if ($continue -ne "Y" -and $continue -ne "y") {
        Write-Host "已取消修复操作，请稍后再试。" -ForegroundColor Yellow
        exit
    }
}

# 2. 执行菜单结构修复SQL脚本
Write-Host "[2/4] 执行菜单结构修复SQL脚本..." -ForegroundColor Yellow

try {
    # 执行SQL命令
    $mysqlCmd = "mysql -u$DB_USER -p$DB_PASSWORD -h$DB_HOST -P$DB_PORT $DB_NAME < `"fix_menu_structure.sql`""
    
    # 使用CMD执行MySQL命令（解决PowerShell中重定向问题）
    $result = cmd /c $mysqlCmd
    
    if ($LASTEXITCODE -ne 0) {
        Write-Host "[错误] SQL脚本执行失败，请检查SQL文件和数据库连接参数。" -ForegroundColor Red
        exit
    }
}
catch {
    Write-Host "[错误] 执行SQL脚本时出现错误: $_" -ForegroundColor Red
    exit
}

# 3. 检查脚本执行结果
Write-Host "[3/4] 检查脚本执行结果..." -ForegroundColor Yellow
Write-Host "SQL脚本已成功执行。已完成以下操作："
Write-Host "- 备份当前菜单表到sys_menu_backup_structure" -ForegroundColor Green
Write-Host "- 将教师管理和学生管理菜单从系统管理移动到第二课堂管理下" -ForegroundColor Green
Write-Host "- 将教师管理和学生管理的菜单类型从`"C`"改为`"M`"" -ForegroundColor Green
Write-Host "- 确保教师管理和学生管理下的按钮权限保持不变" -ForegroundColor Green

# 4. 重启系统以应用更改
Write-Host "[4/4] 重启系统以应用更改..." -ForegroundColor Yellow
$restart = Read-Host "是否重启系统以应用更改？(Y/N)"
if ($restart -eq "Y" -or $restart -eq "y") {
    Write-Host "正在重启系统..." -ForegroundColor Cyan
    
    # 结束当前可能运行的Java进程
    $runningProcess = Get-NetTCPConnection -LocalPort 8089 -ErrorAction SilentlyContinue
    if ($runningProcess) {
        $processId = $runningProcess.OwningProcess
        Stop-Process -Id $processId -Force -ErrorAction SilentlyContinue
        Write-Host "已终止占用8089端口的进程 (PID: $processId)" -ForegroundColor Green
    }
    
    # 启动后端服务
    Start-Process cmd -ArgumentList "/k cd .. && cd scms-admin && mvn spring-boot:run"
    
    # 等待后端服务启动
    Start-Sleep -Seconds 3
    
    # 启动前端服务
    Start-Process cmd -ArgumentList "/k cd scms-ui && npm run dev"
    
    Write-Host "系统已重启，请稍后访问前端页面查看菜单结构更改。" -ForegroundColor Green
}
else {
    Write-Host "系统未重启，您可以稍后手动重启系统以应用更改。" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "修复操作完成，详细说明请查看 fix_menu_structure.sql" -ForegroundColor Cyan
Write-Host "按任意键继续..."
$host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | Out-Null 